package groups.diseases.daobak;

import groups.diseases.Disease;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import com.sun.corba.se.spi.orbutil.fsm.Guard.Result;


public class JDBCDiseasesDAO implements IDiseasesDAO {
	private Connection connection;
	
	public JDBCDiseasesDAO(Connection connection) throws SQLException{
		this.connection = connection;
	}

	public void update(Disease item) throws SQLException {
		Statement stm = connection.createStatement();
		String sql ="update Disease" +
				" set name='"+item.getName()+"', endemic = "+item.isEndemic()+
				" where Id="+item.getId();
		System.out.println(sql);
		stm.executeUpdate(sql);
	}


	public void delete(Disease item) throws SQLException  {
		Statement stm = connection.createStatement();
		stm.executeUpdate("delete from Disease where Id="+item.getId());
	}

	public Vector<Disease> getList() throws SQLException {
		Vector<Disease> diseases = new Vector<Disease>();
		Statement stm = connection.createStatement();
		ResultSet res = stm.executeQuery("select * from Disease");
		
		while(res.next()){
			diseases.add(new Disease(res.getInt(1), res.getString(2), res.getBoolean(3)));
		}
		
		return diseases;
	}


	public Disease getItem(int key) throws SQLException {
		Statement stm = connection.createStatement();
		ResultSet res = stm.executeQuery("select * from Disease where id =" + key);
		
		if(res.next())
			return new Disease(res.getInt(1),res.getString(2), res.getBoolean(3));
		else
			return null;
	}
	
	public Disease create(String name,boolean endemic) throws SQLException {
		Statement stm = connection.createStatement();
		
		ResultSet res = stm.executeQuery("select max(id) from Disease");
		
		int id = res.next()? res.getInt(1)+1 : 0;
		
		stm.executeUpdate("insert into Disease " +
				"(id,name,endemic) values ("+id+"," + "'"+name+"'"+endemic+")");
		
		
		Disease d = new Disease(id, name,endemic);
		stm.close();
		return d;		
	}



}
